package com.walala.logic.server;

import com.walala.logic.common.Global;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 逻辑服务
 * @author KayLi
 */
public class Server {

	private static Logger logger = LoggerFactory.getLogger(Server.class);

	/**
	 * 启动服务
	 * @param ip
	 * @param port
	 */
	public void start(String ip, String port) {

		NioEventLoopGroup boss = new NioEventLoopGroup();
		NioEventLoopGroup worker = new NioEventLoopGroup();

		ServerBootstrap bootstrap = new ServerBootstrap();
		try {
			bootstrap.group(boss, worker).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast("msgDecoder", new LogicProtocolDecoder());// 解码器
                    pipeline.addLast("msgEncoder", new LogicProtocolEncoder());// 编码器
                    pipeline.addLast("idleStateHandler", new IdleStateHandler(3000, 0, 0));// 定时器,秒
                    pipeline.addLast("handler", new ServerHandler());// 消息处理器
                }
            });

			// 配置连接属性
			bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
			bootstrap.childOption(ChannelOption.SO_LINGER, 0);
			bootstrap.childOption(ChannelOption.SO_REUSEADDR, true);
			bootstrap.childOption(ChannelOption.TCP_NODELAY, true);
			bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
			bootstrap.option(ChannelOption.SO_RCVBUF, 1024000);
			bootstrap.option(ChannelOption.SO_SNDBUF, 1024000);
			bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
			bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);//关键是这句

			Channel channel = bootstrap.bind(ip,Integer.valueOf(port)).sync().channel();
			if(channel.isOpen() && channel.isActive()){
				logger.info("逻辑层服务启动,serverIp:[{}],serverPort:[{}]",ip,port);
			}
			channel.closeFuture().sync();
		} catch (Exception e) {
			logger.error("服务启动发生异常",e);
		} finally {
            logger.error("服务已停止");
            worker.shutdownGracefully();
            boss.shutdownGracefully();
        }


	}

}
